package com.mall.fliter;

import com.central.common.utils.GlobalUserContext;
import com.central.common.utils.ResponseUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.entity.Users;
import com.mall.security.TokenManager;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 身份验证过滤器
 */
@Component("tokenAuthFilter")
public class TokenAuthFilter extends BasicAuthenticationFilter {

    @Autowired
    private ObjectMapper objectMapper = new ObjectMapper();

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
//        设置返回中文
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authRequest = null;
        try {
            authRequest= getAuthentication(request);
        } catch (JwtException jwtException) {
            ResponseUtil.responseFailed(new ObjectMapper(), response, "非法伪造token");
            return;
        }
//        判断如果有权限信息，放到权限上下文中
        if(authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //从header获取token
        String token = request.getHeader("token");
        if(token != null) {
            //从token获取用户名
            String username = tokenManager.getUserInfoFromToken(token);
            //从redis获取对应权限列表
            String permissionListStr = (String) redisTemplate.boundHashOps("permission").get(token);
            List<String> permissionList = new ArrayList<>();//权限列表
            try {
                if (permissionListStr != null) {
                    JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, String.class);
                    permissionList = objectMapper.readValue(permissionListStr, javaType);
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            Collection<GrantedAuthority> authority = new ArrayList<>();
            Iterator<String> iterator = permissionList.iterator();//迭代器
            while (iterator.hasNext()) {
                SimpleGrantedAuthority auth = new SimpleGrantedAuthority(iterator.next());
                authority.add(auth);
            }
            //从redis获取用户信息
            String userInfo = (String)redisTemplate.boundValueOps(username).get();
            try {
                Users user = objectMapper.readValue(userInfo, Users.class);
                GlobalUserContext.setUser(user);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            return new UsernamePasswordAuthenticationToken(username,token,authority);
        }

        return null;
    }

}
